interface FlightRealTimeData {
  time: string;
  timeId: string;
  x: number;
  y: number;
  z: number;
  yaw: number;
  roll: number;
  pitch: number;
  customModeText: string;
  groundSpeed: number;
  systemStatusText: string
}

/**
 * 解析轨迹数据字符串为坐标数组
 * @param trackData 轨迹数据字符串
 * @returns 坐标数组 [[x1, y1], [x2, y2], ...]
 */
export function parseTrackData(trackData: string): [number, number][] {
  try {
    // 尝试解析可能包含多个图形元素的轨迹数据
    const trackElements = JSON.parse(trackData);

    // 如果是单个图形元素，包装成数组
    const elements = Array.isArray(trackElements) ? trackElements : [trackElements];

    // 从各种图形元素中提取轨迹点
    const points: [number, number][] = [];

    elements.forEach(element => {
      switch (element.type) {
        case 'rectangle': {
          // 使用块级作用域避免变量重声明
          const { startX, startY, endX, endY } = element.data;
          points.push(
            [startX, startY],
            [endX, startY],
            [endX, endY],
            [startX, endY],
            [startX, startY] // 闭合矩形
          );
          break;
        }

        case 'line': {
          // 使用块级作用域
          const { startX, startY, endX, endY } = element.data;
          points.push(
            [startX, startY],
            [endX, endY]
          );
          break;
        }

        case 'circle': {
          // 使用块级作用域
          const { startX, startY, radius } = element.data;
          const segments = 36 * 3; // 将圆分为36*3段
          for (let i = 0; i <= segments; i++) {
            const angle = (i / segments) * 2 * Math.PI;
            const x = startX + radius * Math.cos(angle);
            const y = startY + radius * Math.sin(angle);
            points.push([x, y]);
          }
          break;
        }

        default:
          console.warn('未知的轨迹元素类型:', element.type);
      }
    });

    return points;
  } catch (error) {
    console.error('解析轨迹数据失败:', error);
    return [];
  }
}

/**
 * 计算规划轨迹与实际轨迹的偏差
 * @param plannedTrack 规划轨迹坐标数组
 * @param realTrack 实际轨迹坐标数组
 * @returns 偏差数组（单位：米）
 */
export function calculateTrackDeviation(
  plannedTrack: [number, number][],
  realTrack: [number, number][]
): number[] {
  const deviations: number[] = [];

  // 对于实飞轨迹中的每个点，找到规划轨迹中最近的点
  realTrack.forEach(([realX, realY]) => {
    let minDistance = Infinity;

    // 遍历规划轨迹，找到最近点
    for (const [plannedX, plannedY] of plannedTrack) {
      const distance = Math.sqrt(
        Math.pow(realX - plannedX, 2) +
        Math.pow(realY - plannedY, 2)
      );

      if (distance < minDistance) {
        minDistance = distance;
      }
    }

    // 记录最小距离作为该点的偏差
    deviations.push(minDistance);
  });

  return deviations;
}

/**
 * 分析偏差数据，计算统计指标
 * @param deviations 偏差数组
 * @returns 包含平均偏差和最大偏差的对象
 */
export function analyzeDeviations(deviations: number[]): { average: number; max: number } {
  if (deviations.length === 0) {
    return { average: 0, max: 0 };
  }

  const sum = deviations.reduce((acc, val) => acc + val, 0);
  const average = sum / deviations.length;
  const max = Math.max(...deviations);

  return { average, max };
}

/**
 * 计算速度偏差统计数据
 * @param realData 实际轨迹数据
 * @param targetSpeed 目标速度
 * @returns 速度偏差统计结果
 */
export function calculateSpeedDeviations(
  realData: FlightRealTimeData[],
  targetSpeed: number
): { average: number; variance: number; max: number } {
  if (realData.length === 0) {
    return { average: 0, variance: 0, max: 0 };
  }

  // 强制转换为数字并过滤无效值
  const validSpeeds = realData
    .map(data => Number(data.groundSpeed)) // 关键修改：强制转换为数字
    .filter(speed => !isNaN(speed));

  if (validSpeeds.length === 0) {
    return { average: 0, variance: 0, max: 0 };
  }

  // 计算平均速度
  const sum = validSpeeds.reduce((acc, speed) => acc + speed, 0);
  console.log("速度和：", sum);
  const average = sum / validSpeeds.length;
  console.log("平均速度：", average);

  // 计算方差
  const squaredDiffs = validSpeeds.map(speed => Math.pow(speed - targetSpeed, 2));
  const variance = squaredDiffs.reduce((acc, diff) => acc + diff, 0) / validSpeeds.length;

  // 计算最大偏差
  const maxDeviation = Math.max(...validSpeeds.map(speed => Math.abs(speed - targetSpeed)));

  return { average, variance, max: maxDeviation };
}

/**
 * 计算时间偏差
 * @param plannedTrack 规划轨迹
 * @param realData 实际轨迹数据
 * @param targetSpeed 目标速度
 * @returns 时间偏差统计结果
 */
export function calculateTimeDeviation(
  plannedTrack: [number, number][],
  realData: FlightRealTimeData[],
  targetSpeed: number
): { plannedTime: number; actualTime: number; deviation: number; deviationPercent: number } {
  if (plannedTrack.length < 2 || realData.length < 2) {
    return {
      plannedTime: 0,
      actualTime: 0,
      deviation: 0,
      deviationPercent: 0
    };
  }

  // 计算规划轨迹总长度
  let totalDistance = 0;
  for (let i = 0; i < plannedTrack.length - 1; i++) {
    const [x1, y1] = plannedTrack[i];
    const [x2, y2] = plannedTrack[i + 1];
    totalDistance += Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
  }

  // 计算预计时间（秒）
  const plannedTime = totalDistance / (targetSpeed || 0.1); // 避免除零

  // 获取实际飞行的开始和结束时间
  const startTime = new Date(realData[0].time);
  const endTime = new Date(realData[realData.length - 1].time);

  // 计算实际时间（秒）
  const actualTime = (endTime.getTime() - startTime.getTime()) / 1000;

  // 计算时间偏差
  const deviation = actualTime - plannedTime;
  const deviationPercent = (deviation / plannedTime) * 100;

  return {
    plannedTime,
    actualTime,
    deviation,
    deviationPercent
  };
}
